package com.estore.network;

import com.estore.service.ProductService;
import com.estore.model.Product;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;

public class EStoreServer {
    private final ProductService productService;
    private final int port;
    private boolean isRunning;

    public EStoreServer(int port) {
        this.port = port;
        this.productService = new ProductService();
        this.isRunning = false;
    }

    public void start() {
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            isRunning = true;
            System.out.println("电子商城服务器启动成功，监听端口: " + port);
            System.out.println("等待客户端连接...");

            while (isRunning) {
                try {
                    Socket clientSocket = serverSocket.accept();
                    System.out.println("客户端连接成功: " + clientSocket.getInetAddress().getHostAddress());

                    // 为每个客户端创建新线程处理
                    new Thread(() -> handleClient(clientSocket)).start();
                } catch (IOException e) {
                    if (isRunning) {
                        System.err.println("接受客户端连接时发生错误: " + e.getMessage());
                    }
                }
            }
        } catch (IOException e) {
            System.err.println("服务器启动失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    public void stop() {
        isRunning = false;
        System.out.println("服务器正在关闭...");
    }

    private void handleClient(Socket clientSocket) {
        try (ObjectInputStream input = new ObjectInputStream(clientSocket.getInputStream());
             ObjectOutputStream output = new ObjectOutputStream(clientSocket.getOutputStream())) {

            System.out.println("开始处理客户端请求: " + clientSocket.getInetAddress().getHostAddress());

            while (isRunning) {
                try {
                    // 读取客户端请求
                    String request = (String) input.readObject();
                    System.out.println("收到客户端请求: " + request);

                    // 根据请求类型处理
                    Object response = processRequest(request);

                    // 发送响应
                    output.writeObject(response);
                    output.flush();
                    System.out.println("请求处理完成: " + request);

                } catch (EOFException e) {
                    // 客户端断开连接
                    System.out.println("客户端断开连接: " + clientSocket.getInetAddress().getHostAddress());
                    break;
                } catch (ClassNotFoundException e) {
                    System.err.println("读取客户端请求时发生错误: " + e.getMessage());
                    sendError(output, "无效的请求格式");
                } catch (Exception e) {
                    System.err.println("处理请求时发生错误: " + e.getMessage());
                    sendError(output, "服务器内部错误: " + e.getMessage());
                }
            }

        } catch (IOException e) {
            System.err.println("处理客户端连接时发生IO错误: " + e.getMessage());
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                System.err.println("关闭客户端连接时发生错误: " + e.getMessage());
            }
        }
    }

    private Object processRequest(String request) {
        try {
            switch (request) {
                case "GET_ALL_PRODUCTS":
                    return productService.getAllProducts();

                case "GET_AVAILABLE_PRODUCTS":
                    return productService.getAvailableProducts();

                case "GET_PRODUCT_COUNT":
                    return productService.getProductCount();

                case "GET_ALL_TAGS":
                    return productService.getAllTags();

                default:
                    if (request.startsWith("SEARCH_BY_NAME:")) {
                        String keyword = request.substring("SEARCH_BY_NAME:".length());
                        return productService.searchProductsByName(keyword);
                    }

                    if (request.startsWith("SEARCH_BY_TAG:")) {
                        String tag = request.substring("SEARCH_BY_TAG:".length());
                        return productService.searchProductsByTag(tag);
                    }

                    if (request.startsWith("FIND_PRODUCT_BY_ID:")) {
                        String productId = request.substring("FIND_PRODUCT_BY_ID:".length());
                        return productService.findProductById(productId);
                    }

                    if (request.startsWith("CHECK_STOCK:")) {
                        String productId = request.substring("CHECK_STOCK:".length());
                        Product product = productService.findProductById(productId);
                        return product != null ? product.getStock() : -1;
                    }

                    throw new IllegalArgumentException("未知的请求类型: " + request);
            }
        } catch (Exception e) {
            throw new RuntimeException("处理请求时发生错误: " + e.getMessage(), e);
        }
    }

    private void sendError(ObjectOutputStream output, String errorMessage) {
        try {
            output.writeObject("ERROR:" + errorMessage);
            output.flush();
        } catch (IOException ioException) {
            System.err.println("发送错误信息失败: " + ioException.getMessage());
        }
    }

    public static void main(String[] args) {
        int port = 8888;
        if (args.length > 0) {
            try {
                port = Integer.parseInt(args[0]);
            } catch (NumberFormatException e) {
                System.err.println("无效的端口号，使用默认端口: 8888");
            }
        }

        EStoreServer server = new EStoreServer(port);

        // 添加关闭钩子，确保服务器优雅关闭
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("\n接收到关闭信号，正在关闭服务器...");
            server.stop();
        }));

        server.start();
    }
}